package gulimall.service.impl;

import gulimall.entity.Attr;
import gulimall.entity.ProductAttrValue;
import gulimall.mapper.AttrMapper;
import gulimall.mapper.ProductAttrValueMapper;
import gulimall.service.ProductAttrValueService;
import gulimall.utils.PageUtils;
import gulimall.utils.Query;
import gulimall.vo.spusave.BaseAttrs;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueMapper, ProductAttrValue> implements ProductAttrValueService {

    @Resource
    private AttrMapper attrMapper;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValue> page = this.page(
                new Query<ProductAttrValue>().getPage(params),
                new QueryWrapper<ProductAttrValue>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存spu规格参数
     *
     * @param baseAttrs
     * @param spuId
     */
    @Override
    @Transactional
    public void saveAttrs(Long spuId, List<BaseAttrs> baseAttrs) {
        List<ProductAttrValue> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValue productAttrValue = new ProductAttrValue();
            productAttrValue.setSpuId(spuId);
            productAttrValue.setQuickShow(attr.getShowDesc());
            productAttrValue.setAttrValue(attr.getAttrValues());
            productAttrValue.setAttrSort(0);
            productAttrValue.setAttrId(attr.getAttrId());

            //获取Attr具体信息
            Attr byId = attrMapper.selectById(attr.getAttrId());
            productAttrValue.setAttrName(byId.getAttrName());
            return productAttrValue;
        }).collect(Collectors.toList());
        this.saveBatch(collect);
    }

    /**
     * 修改商品规格
     *
     * @param spuId
     * @param productAttrValues
     */
    @Override
    @Transactional
    public void updateProductAttr(String spuId, List<ProductAttrValue> productAttrValues) {
        //删除这个spuId之前对应的所有属性
        baseMapper.delete(new QueryWrapper<ProductAttrValue>()
                .lambda().eq(ProductAttrValue::getSpuId, spuId)
        );

        //给新的spu规格参数设置spuId
        productAttrValues = productAttrValues.stream().peek(attrValue -> {
            attrValue.setSpuId(Long.valueOf(spuId));
        }).collect(Collectors.toList());

        //保存新的spu规格参数
        this.saveBatch(productAttrValues);
    }

}